package fitnesshub.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import fitnesshub.exception.RelatedCoursesExist;
import fitnesshub.mapper.CoachMapper;
import fitnesshub.mapper.CourseMapper;
import fitnesshub.pojo.dto.AddCoachDTO;
import fitnesshub.pojo.dto.CoachPageQueryDTO;
import fitnesshub.pojo.entity.Coach;
import fitnesshub.result.PageResult;
import fitnesshub.service.CoachService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class CoachServiceImpl implements CoachService {
    @Autowired
    private CoachMapper coachMapper;

    @Autowired
    private CourseMapper courseMapper;

    /**
     * 教练分页
     * @param coachPageQueryDTO
     * @return
     */
    @Override
    public PageResult page(CoachPageQueryDTO coachPageQueryDTO) {
        PageHelper.startPage(coachPageQueryDTO.getPage(), coachPageQueryDTO.getPageSize());
        Page<Coach> page = coachMapper.pageQuery(coachPageQueryDTO);
        long total = page.getTotal();
        List<Coach> records = page.getResult();
        return new PageResult(total, records);
    }

    /**
     * 根据id查询教练
     * @param coachId
     * @return
     */
    @Override
    public Coach getById(Integer coachId) {
        return coachMapper.getById(coachId);
    }

    /**
     * 新增教练
     * @param addCoachDTO
     */
    @Override
    public void addACoach(AddCoachDTO addCoachDTO) {
        Coach coach = new Coach();
        // 对象属性拷贝
        BeanUtils.copyProperties(addCoachDTO, coach);
        coach.setCreateTime(LocalDateTime.now());
        coach.setUpdateTime(LocalDateTime.now());

        coachMapper.insert(coach);
    }

    /**
     * 编辑教练
     * @param coach
     * @return
     */
    @Override
    public void editCoach(Coach coach) {
        coach.setUpdateTime(LocalDateTime.now());
        coachMapper.update(coach);
    }

    /**
     * 根据id删除教练
     * @param coachId
     * @return
     */
    @Override
    public void deleteById(Integer coachId) {
        // 检查是否有关联的课程
        if (courseMapper.existsByCoachId(coachId) > 0) {
            throw new RelatedCoursesExist("无法删除教练，因为该教练还有在授课程。");
        }

        // 删除教练
        coachMapper.deleteById(coachId);
    }

    /**
     * 检查教练是否存在
     * @param coachId
     * @return
     */
    @Override
    public boolean checkCoachExists(Integer coachId) {
        return coachMapper.getById(coachId) != null;
    }
}
